package org.duang.lock;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

/**
 * 测试用
 * @author pc_01
 */
public class LockJob{

	private final String name;
	private final InterProcessLock lock;
	
	public LockJob(CuratorFramework curator, String lockPath, String name)  {
		this.name = name;
		this.lock = new InterProcessMutex(curator, lockPath);
	}
	
	/***
	 * 
	 * @param time		锁等待时间(秒)
	 */
	public void doWork(long waitTimeout) throws Exception {
		
		if(!lock.acquire(waitTimeout, TimeUnit.SECONDS)) {
//			System.out.println( name + " wait " + waitTimeout + " seconds, catn't get to lock, give up...");
			throw new IllegalStateException( name + " wait " + waitTimeout + " seconds, catn't get to lock, give up...");
		}
		try{
			// 模拟job执行时间0-2000毫秒
			int exeTime = new Random().nextInt(2000);
//			int exeTime = 4000;
			Thread.sleep(exeTime);
			System.out.println(name + "开始执行,预计执行时间= " + exeTime + "毫秒----------");
		} finally {
			lock.release();		//释放锁
		}
		
	}

}
